import { getCurrentLoginInformations } from '@/api/session'

const state = {
  application: null,
  tenant: null,
  tenantId: null,
  user: null,
  firstLogin: true,
  userId: null
}

const mutations = {
  SET_APPLICATION: (state, application) => {
    state.application = application
  },
  SET_TENANT: (state, tenant) => {
    state.tenant = tenant
    state.tenantId = tenant ? tenant.id : null
  },
  SET_USER: (state, user) => {
    state.user = user
    state.userId = user ? user.id : null
  },
  SET_FIRST_LOGIN: (state, firstLogin) => {
    state.firstLogin = firstLogin
  }
}

const actions = {
  init({ commit }) {
    return new Promise((resolve, reject) => {
      getCurrentLoginInformations().then(data => {
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        // commit('SET_APPLICATION', application)
        // commit('SET_TENANT', tenant)
        commit('SET_USER', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
